/**
 * 动态表单Javascript，负责读取表单元素、启动流程
 */
$(function () {
    $('.startup-process').button({
        icons: {
            primary: 'ui-icon-play'
        }
    }).click(showStartupProcessDialog);
});

$(function () {
    /*JQuery 限制文本框只能输入数字*/
    $(".NumText").keyup(function () {
        $(this).val($(this).val().replace(/D|^0/g, ''));
    }).bind("paste", function () {  //CTR+V事件处理
        $(this).val($(this).val().replace(/D|^0/g, ''));
    }).css("ime-mode", "disabled"); //CSS设置输入法不可用

    /*JQuery 限制文本框只能输入数字和小数点*/
    $(".NumDecText").keyup(function () {
        $(this).val($(this).val().replace(/[^0-9.]/g, ''));
    }).bind("paste", function () {  //CTR+V事件处理
        $(this).val($(this).val().replace(/[^0-9.]/g, ''));
    }).css("ime-mode", "disabled"); //CSS设置输入法不可用
});

/**
 * 打开启动流程
 */

function showStartupProcessDialog() {
    var $ele = $(this);
    $('<div/>', {
        'class': 'dynamic-form-dialog',
        title: '启动流程[' + $ele.parents('tr').find('.process-name').text() + ']',
        html: '<span class="ui-loading">正在读取表单……</span>'
    }).dialog({
        modal: true,
        width: 700,
        height: $.common.window.getClientHeight() * (2 / 3),
        open: function () {
            // 获取json格式的表单数据，就是流程定义中的所有field
            readFormFields.call(this, $ele.parents('tr').find('.process-id').text());
        },
        buttons: [{
            text: '启动流程',
            click: sendStartupRequest
        }]
    });
}

/**
 * 读取表单字段
 */

function readFormFields(processDefinitionId) {
    var dialog = this;

    // 清空对话框内容
    $('.dynamic-form-dialog').html("<form class='dynamic-form' method='post'><table class='dynamic-form-table'></table></form>");
    var $form = $('.dynamic-form');

    // 设置表单提交id,表单提交启动流程
    $form.attr('action', ctx + '/form/dynamic/start-process/' + processDefinitionId);

    // 添加隐藏域
    if ($('#processType').length == 0) {
        $('<input/>', {
            'id': 'processType',
            'name': 'processType',
            'type': 'hidden'
        }).val(processType).appendTo($form);
    }

    // 读取启动时的表单
    $.getJSON(ctx + '/form/dynamic/get-form/start/' + processDefinitionId, function (data) {
        var trs = "";
        /*   $.each(data.form.formProperties, function () {
               var className = this.required === true ? "required" : "";
               trs += "<tr>" + createFieldHtml(data, this, className);
               if (this.required === true) {
                   trs += "<span style='color:red'>*</span>";
               }
               trs += "</td></tr>";
           });*/
        //实现一行分成2个字段进行显示
        for (var i = 0; i < data.form.formProperties.length; i++) {
            var className = this.required === true ? "required" : "";
            if (i % 2 == 0) {
                trs += "<tr>" + createFieldHtml(data, data.form.formProperties[i], className);
                if (this.required === true) {
                    trs += "<span style='color:red'>*</span>";
                }
            } else {
                trs += createFieldHtml(data, data.form.formProperties[i], className);
                if (this.required === true) {
                    trs += "<span style='color:red'>*</span>";
                }
                trs += "</td></tr>";
            }
        }
        if (data.form.formProperties.length % 2 == 0 && data.form.formProperties.length > 0) {
            trs += "</td></tr>";
        }
        // 添加table内容
        $('.dynamic-form-table').html(trs).find('tr').hover(function () {
            $(this).addClass('ui-state-hover');
        }, function () {
            $(this).removeClass('ui-state-hover');
        });

        // 初始化日期组件
        $form.find('.dateISO').datepicker();

        // 表单验证
        $form.validate($.extend({}, $.common.plugin.validator));
    });
}

/**
 * form对应的string/date/long/enum/boolean类型表单组件生成器,新增double，只能输入数字和小数
 * fp_的意思是form paremeter
 */
var formFieldCreator = {
    string: function (formData, prop, className) {
        var result = "<td width='120'>" + prop.name + "：</td><td><input type='text' id='" + prop.id + "' name='fp_" + prop.id + "' class='" + className + "' />";
        return result;
    },
    date: function (formData, prop, className) {
        var result = "<td>" + prop.name + "：</td><td><input type='text' id='" + prop.id + "' name='fp_" + prop.id + "' class='dateISO " + className + "' />";
        return result;
    },
    'enum': function (formData, prop, className) {
        console.log(prop);
        var result = "<td width='120'>" + prop.name + "：</td>";
        if (prop.writable === true) {
            result += "<td><select id='" + prop.id + "' name='fp_" + prop.id + "' class='" + className + "'>";
            //result += "<option>" + datas + "</option>";

            $.each(formData['enum_' + prop.id], function (k, v) {
                result += "<option value='" + k + "'>" + v + "</option>";
            });

            result += "</select>";
        } else {
            result += "<td>" + prop.value;
        }
        return result;
    },
    'users': function (formData, prop, className) {
        var result = "<td width='120'>" + prop.name + "：</td><td><input type='text' id='" + prop.id + "' name='fp_" + prop.id + "' class='" + className + "' />";
        return result;
    },
    double: function (formData, prop, className) {
        var result = "<td>" + prop.name + "：</td><td><input type='text' id='" + prop.id + "' name='fp_" + prop.id + "' class='NumDecText " + className + "' />";
        return result;
    }
};

/**
 * 生成一个field的html代码
 */

function createFieldHtml(formData, prop, className) {
    return formFieldCreator[prop.type.name](formData, prop, className);
}

/**
 * 发送启动流程请求
 */

function sendStartupRequest() {
    if ($(".dynamic-form").valid()) {
        $('.dynamic-form').submit();
    }
}